package com.xulu.romance.controller;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xulu.romance.constants.Constant;
import com.xulu.romance.pojo.User;
import com.xulu.romance.pojo.UserLog;
import com.xulu.romance.service.UserLogService;
import com.xulu.romance.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@RestController
@CrossOrigin
@RequestMapping("/api/userLog")
@Api(tags = "用户日志")
@Slf4j
public class UserLogController {

    @Autowired
    private UserLogService userLogService;

    @GetMapping("/findAll")
    @ApiOperation("查询所有")
    public R findAll() {
        List<UserLog> userLogList = userLogService.list();
        return R.ok().put("userLogList", userLogList);
    }

    @GetMapping("/findAll/{currentPage}/{size}")
    @ApiOperation("分页查询")
    public R findPage(@PathVariable Long currentPage, @PathVariable Long size, UserLog condition) {
        // 创建分页对象
        IPage<UserLog> page = new Page<>(currentPage, size);

        // 构建查询条件
        QueryWrapper<UserLog> queryWrapper = new QueryWrapper<>();
        if (condition != null) {
            // 如果条件不为空，添加相应的查询条件
            if (StringUtils.isNotBlank(condition.getUserName())) {
                queryWrapper.like("user_name", condition.getUserName());
            }
        }
        // 根据创建时间降序排序
        queryWrapper.orderByDesc("login_time");

        // 执行分页查询
        IPage<UserLog> userLogIPage = userLogService.page(page, queryWrapper);

        // 获取查询结果
        List<UserLog> userLogList = userLogIPage.getRecords();
        long total = userLogIPage.getTotal();


        // 返回结果
        return Objects.requireNonNull(R.ok().put("userLogList", userLogList)).put("count", total);
    }

    @GetMapping("/findById/{id}")
    @ApiOperation("根据id查询")
    public R findById(@PathVariable Integer id) {
        UserLog userLog = userLogService.getById(id);
        return R.ok().put("userLog", userLog);
    }


    @PostMapping("/save")
    @ApiOperation("添加用户日志")
    public R save(@RequestBody UserLog userLog) {

        try {
            boolean save = userLogService.save(userLog);
            if (!save) {
                return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.SAVE_FAILURE);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.SAVE_SUCCESS);
    }

    @PostMapping("/update")
    @ApiOperation("更新用户日志")
    public R update(@RequestBody UserLog userLog) {
        boolean save = userLogService.updateById(userLog);
        if (!save) {
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.UPDATE_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.UPDATE_SUCCESS);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除用户日志")
    public R delete(@PathVariable Integer id) {
        boolean save = userLogService.removeById(id);
        if (!save) {
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.DELETE_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.DELETE_SUCCESS);
    }

    @PostMapping("/deleteBatch")
    @ApiOperation("批量删除用户日志")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        boolean save = userLogService.removeBatchByIds(ids);
        if (!save) {
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.DELETE_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.DELETE_SUCCESS);
    }

    @GetMapping("/export")
    @ApiOperation("导出用户日志")
    public void export(HttpServletResponse response) throws Exception {
        List<UserLog> list = userLogService.list();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("id", "id");
        writer.addHeaderAlias("userId", "用户id");
        writer.addHeaderAlias("userName", "用户名");
        writer.addHeaderAlias("loginTime", "登录时间");
        writer.addHeaderAlias("ipAddress", "ip地址");
        writer.addHeaderAlias("deviceInfo", "登录设备");
        writer.addHeaderAlias("location", "登录地址");
        writer.addHeaderAlias("uri", "访问地址");
        writer.addHeaderAlias("requestMethod", "请求方式");
        writer.addHeaderAlias("loginMethod", "请求方法");

        writer.setOnlyAlias(true);

        writer.write(list, true);

        // 设置response参数
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String name = URLEncoder.encode("用户日志", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + name + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    @PostMapping("/import")
    @ApiOperation("导入用户日志")
    public R importUser(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<UserLog> userLogList = reader.readAll(UserLog.class);
        boolean save = userLogService.saveBatch(userLogList);
        if (!save) {
            return Objects.requireNonNull(new R().put("code", Constant.FAILURE_CODE)).put("message", Constant.IMPORT_FAILURE);
        }
        return Objects.requireNonNull(new R().put("code", Constant.SUCCESS_CODE)).put("message", Constant.IMPORT_SUCCESS);
    }



}
